package com.example.lte.api;

import cn.dev33.satoken.stp.StpUtil;
import com.example.lte.config.BusinessLogic;
import com.example.lte.config.SysBusinessUnitEnum;
import com.example.lte.entity.UserEntity;
import com.example.lte.po.SaveUserPO;
import com.example.lte.po.UserReq;
import com.example.lte.restful.APIException;
import com.example.lte.restful.ResultCodeEnum;
import com.example.lte.service.IRoleService;
import com.example.lte.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;

    //{
//    "code": 0,
//    "msg": "操作成功",
//    "data": {
//        "content": [
//            {
//                "id": 16,
//                "name": "温1柔",
//                "account": "ert34",
//                "password": "2323",
//                "addTime": null,
//                "updateTime": null,
//                "version": null
//            }
//        ],
//        "pageable": {
//            "sort": {
//                "sorted": true,
//                "unsorted": false,
//                "empty": false
//            },
//            "offset": 10,
//            "pageSize": 10,
//            "pageNumber": 1,
//            "paged": true,
//            "unpaged": false
//        },
//        "last": true,
//        "totalPages": 2,
//        "totalElements": 11,
//        "number": 1,
//        "size": 10,
//        "sort": {
//            "sorted": true,
//            "unsorted": false,
//            "empty": false
//        },
//        "numberOfElements": 1,
//        "first": false,
//        "empty": false
//    },
//    "timestamp": 1602990260240
//}
    @GetMapping("/page")
    @ApiOperation(value = "查询用户信息",notes = "详细描述-分页查询用户表")
    @BusinessLogic(value = "查询用户列表", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public Page<UserEntity> findPage(UserReq userReq) {
        StpUtil.checkLogin();
        UserEntity u = UserEntity.builder()
                .account(userReq.getAccount())
                .id(userReq.getUserId())
                .name(userReq.getName())
                .build();
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(userReq.getPageNo(), userReq.getPageSize(), sort);
        return iUserService.findByCondition(u, pageable);
    }


    @PostMapping("/saveOne")
    @ApiOperation("添加新用户")
    @BusinessLogic(value = "后台添加用户", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public String addUser(@RequestBody @Valid SaveUserPO saveUserPO) {
        StpUtil.checkLogin();
        UserEntity u = UserEntity.builder()
                .account(saveUserPO.getAccount())
                .name(saveUserPO.getName())
                .sex(saveUserPO.getSex())
                .password("10470C3B4B1FED12C3BAAC014BE15FAC67C6E815")
                .build();
        UserEntity dbUser = iUserService.saveOne(u);
        return dbUser.getId() + "用户已添加，初始密码123456,请及时修改密码";
    }

    /**
     * 修改用户name和sex
     * localhost:8081/lte/user/updateNameAndSexById?name=王不二&sex=0&id=11
     * {
     * "code": 0,
     * "msg": "操作成功",
     * "data": "修改用户name和sex成功",
     * "timestamp": 1604022990124
     * }
     *
     * @param name 用户name
     * @param sex  用户sex: 0女 1男
     * @param id   用户id
     * @return String
     */
    @PutMapping("/updateNameAndSexById")
    @ApiOperation(value = "修改用户name和sex",notes = "详细描述-修改用户name和sex")
    @BusinessLogic(value = "修改用户name和sex", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public String updateUser(@ApiParam("用户名") @RequestParam String name,
                             @ApiParam("性别") @RequestParam int sex,
                             @ApiParam("用户ID") @RequestParam Long id) {
        StpUtil.checkLogin();
        iUserService.updateNameAndSexById(name, sex, id);
        return "修改用户name和sex成功";
    }


    /**
     * 支持删除1个或多个用户
     *
     * @param ids userIds
     * @return String
     */
    @DeleteMapping("/delByIds")
    @ApiOperation(value = "删除1个或多个用户",notes = "详细描述-删除1个或多个用户")
    @BusinessLogic(value = "删除1个或多个用户", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public String delByUserIds(@RequestParam Long[] ids) {
        StpUtil.checkLogin();

        boolean isOnline = iUserService.isOnlineToday(ids);
        if (!isOnline) {
            log.warn("删除角色关联关系");
            iRoleService.delByUserIds(ids);
            log.warn("删除用户");
            iUserService.delByIds(ids);
        } else {
            throw new APIException(ResultCodeEnum.USER_IS_USING);
        }
        return "删除1个或多个用户成功";
    }


    @GetMapping("/rollBackDefaultPass")
    @ApiOperation(value = "恢复默认密码",notes = "详细描述-恢复默认密码")
    @BusinessLogic(value = "恢复默认密码", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public String rollBackDefaultPass(@RequestParam Long[] ids) {
        iUserService.updateDefaultPassByIds(ids);
        return "恢复默认密码成功!";
    }


    @GetMapping("/addRelRoleIds")
    @ApiOperation(value = "用户关联角色",notes = "详细描述-用户关联角色")
    @BusinessLogic(value = "用户关联角色", businessUnit = SysBusinessUnitEnum.USER_UNIT)
    public String addRelRoleIds(@RequestParam Long[] roleIds, @RequestParam Long userId) {
        StpUtil.checkLogin();
        iRoleService.addRelRoleIds(roleIds, userId);
        return "用户关联角色成功!";
    }


}
